package generate

import (
	"bytes"
	"os"
	"path"
	"text/template"
)

// var srcPath = "../v9.3.7.5_20220228"
var srcPath = []string{"../v9.3.8.7_20230117", "quote_v9.3.1.4_20190925"}

// readFile 文件先手动转为 UTF8
//
//	@param fileNames
//	@return string
func readFile(fileNames ...string) string {
	var str string
	for _, fileName := range fileNames {
		var fileFullPath string
		for _, v := range srcPath {
			if _, err := os.Stat(path.Join(v, fileName)); err == nil {
				fileFullPath = path.Join(v, fileName)
				break
			}
		}
		bs, err := os.ReadFile(fileFullPath)
		if err != nil {
			panic(err)
		}
		str += string(bs)
	}
	return str
}

func writeTmpl(tplFile string, writeToFile string, data any, funcMaps ...template.FuncMap) {
	var err error
	t := template.New(tplFile).Delims("[[", "]]")
	// funcMap 加入 Funcs
	for _, fm := range funcMaps {
		t = t.Funcs(fm)
	}
	if t, err = t.ParseFiles(tplFile); err != nil {
		panic(err)
	}

	buf := bytes.Buffer{}
	if err = t.Execute(&buf, data); err != nil {
		panic(err)
	}
	// 解决 & 生成tmp 后多出的 amp;
	// 用 text/template 替代 html/template 解决
	// bs := buf.Bytes()
	// bs = bytes.ReplaceAll(bs, []byte("amp;"), []byte(""))
	if err = os.WriteFile(writeToFile, buf.Bytes(), os.ModePerm); err != nil {
		panic(err)
	}
}
